<template>
  <div class="game-management">
    <!-- 搜索和操作区域 -->
    <div class="toolbar">
      <el-input
          v-model="searchKeyword"
          placeholder="搜索游戏名称或开发者"
          clearable
          style="width: 250px; margin-right: 10px;"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="handleAdd">添加游戏</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
        :data="tableData"
        border
        style="width: 100%; margin-top: 20px;"
        :default-sort="{ prop: 'gameId', order: 'ascending' }"
    >
      <el-table-column
          prop="gameId"
          label="ID"
          width="80"
          sortable
      />
      <el-table-column
          prop="gameName"
          label="游戏名称"
          width="150"
      />
      <el-table-column
          prop="platform"
          label="平台"
          width="150"
      >
        <template #default="scope">
          <div v-for="platform in scope.row.platform" :key="platform" style="display: inline-block; margin-right: 5px;">
            <el-tag size="small">{{ platform }}</el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column
          prop="type"
          label="类型"
          width="150"
      >
        <template #default="scope">
          <div v-for="type in scope.row.type" :key="type" style="display: inline-block; margin-right: 5px;">
            <el-tag size="small">{{ type }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column
          prop="intro"
          label="简介"
          width="200"
      />
      <el-table-column
          prop="score"
          label="评分"
          width="100"
      />
      <el-table-column
          prop="coverImage"
          label="封面图"
          width="150"
      >
        <template #default="scope">
          <img
              :src="getImageUrl(scope.row.coverImage)"
              alt="封面图"
              style="width: 40px; height: 40px; object-fit: cover;"
          />
        </template>
      </el-table-column>
      <el-table-column
          prop="releaseTime"
          label="发布时间"
          width="150"
      />
      <el-table-column
          prop="developer"
          label="开发商"
          width="150"
      />
      <el-table-column
          prop="create_time"
          label="创建时间"
          width="180"
      />
      <el-table-column
          prop="update_time"
          label="更新时间"
          width="180"
      />
      <el-table-column
          label="操作"
          width="180"
      >
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px;"
    />

    <!-- 添加/编辑对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="600px"
    >
      <el-form
          :model="form"
          :rules="rules"
          ref="formRef"
          label-width="100px"
      >
        <el-form-item label="游戏名称" prop="gameName">
          <el-input v-model="form.gameName" />
        </el-form-item>
        <el-form-item label="平台" prop="platform">
          <el-select
              v-model="form.platform"
              placeholder="请选择平台"
              multiple
              style="width: 100%"
          >
            <el-option label="端游" value="端游" />
            <el-option label="手游" value="手游" />
            <el-option label="网页游戏" value="网页游戏" />
            <el-option label="单机" value="单机" />
            <el-option label="主机游戏" value="主机游戏" />
            <el-option label="VR游戏" value="VR游戏" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select
              v-model="form.type"
              placeholder="请选择类型"
              multiple
              style="width: 100%"
          >
            <el-option label="角色扮演" value="角色扮演" />
            <el-option label="动作冒险" value="动作冒险" />
            <el-option label="策略" value="策略" />
            <el-option label="模拟经营" value="模拟经营" />
            <el-option label="射击" value="射击" />
            <el-option label="体育竞技" value="体育竞技" />
            <el-option label="休闲益智" value="休闲益智" />
            <el-option label="卡牌" value="卡牌" />
            <el-option label="音乐节奏" value="音乐节奏" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <el-input v-model="form.intro" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="评分" prop="score">
          <el-input-number v-model="form.score" :min="0" :max="10" :step="0.1" />
        </el-form-item>
        <el-form-item label="封面图" prop="coverImage">
          <el-input v-model="form.coverImage" placeholder="请输入图片URL" />
        </el-form-item>
        <el-form-item label="发布时间" prop="releaseTime">
          <el-date-picker
              v-model="form.releaseTime"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="开发商" prop="developer">
          <el-input v-model="form.developer" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted} from 'vue';
import axios from '@/utils/axios';

// 表格数据
const tableData = ref([]);

// 搜索关键词
const searchKeyword = ref('');

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('添加游戏');
const form = reactive({
  gameId: 0,
  gameName: '',
  platform: [], // 多选数组
  type: [], // 多选数组
  intro: '',
  score: 8.5,
  coverImage: '',
  releaseTime: '',
  developer: ''
});

// 表单验证规则
const rules = {
  gameName: [
    { required: true, message: '请输入游戏名称', trigger: 'blur' }
  ],
  platform: [
    { required: true, message: '请选择至少一个平台', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择至少一个类型', trigger: 'change' }
  ],
  intro: [
    { required: true, message: '请输入简介', trigger: 'blur' }
  ],
  score: [
    { required: true, message: '请输入评分', trigger: 'blur' }
  ],
  coverImage: [
    { required: true, message: '请输入封面图URL', trigger: 'blur' }
  ],
  releaseTime: [
    { required: true, message: '请选择发布时间', trigger: 'change' }
  ],
  developer: [
    { required: true, message: '请输入开发商', trigger: 'blur' }
  ]
};

// 获取图片URL
const getImageUrl = (imageName: string) => {
  // 这里可以根据实际的图片存储路径进行调整
  return `https://example.com/images/${imageName}.jpg`;
};

// 将数组转换为文本显示
const formatArrayToText = (arr: string[]) => {
  if (!arr || arr.length === 0) return '';
  return arr.join('/');
};

// 将文本转换为数组
const formatTextToArray = (text: string) => {
  if (!text) return [];
  return text.split('/');
};

// 将后端数据转换为前端格式
const transformGameData = (data: any[]) => {
  return data.map(item => ({
    gameId: item.gameId,
    gameName: item.gameName,
    // 将平台和类型文本转换为数组
    platform: formatTextToArray(item.platform),
    type: formatTextToArray(item.type),
    intro: item.intro,
    score: item.score,
    coverImage: item.coverImage,
    releaseTime: item.releaseTime ? item.releaseTime.split('T')[0] : '',
    developer: item.developer,
    create_time: item.createTime ? new Date(item.createTime).toLocaleString() : '',
    update_time: item.updateTime ? new Date(item.updateTime).toLocaleString() : ''
  }));
};

// 方法
const handleSearch = () => {
  currentPage.value = 1;
  fetchGameList();
};

const fetchGameList = async () => {
  try {
    // 将搜索关键词传递给后端
    const res = await axios.get('/admin/games/list', {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        keyword: searchKeyword.value // 添加搜索关键词参数
      }
    });

    // 转换数据格式
    if (res.data.records) {
      tableData.value = transformGameData(res.data.records);
      total.value = res.data.total;
    } else {
      tableData.value = [];
      total.value = 0;
    }

    console.log(res);
    console.log(tableData.value);
  } catch (error) {
    console.error(error);
  }
};

const handleAdd = () => {
  dialogTitle.value = '添加游戏';
  form.gameId = 0;
  form.gameName = '';
  form.platform = [];
  form.type = [];
  form.intro = '';
  form.score = 8.5;
  form.coverImage = '';
  form.releaseTime = '';
  form.developer = '';
  dialogVisible.value = true;
};

const handleEdit = (row: any) => {
  dialogTitle.value = '编辑游戏';
  // 直接使用行数据，因为已经在tableData中转换过了
  const editForm = { ...row };
  Object.assign(form, editForm);
  dialogVisible.value = true;
};

const handleDelete = async (row: any) => {
  // 删除逻辑
  try{
    console.log(row.gameId)
    await axios.delete('/admin/games/del?gameId='+row.gameId)
    await fetchGameList()
  }catch (e) {

  }

};

const handlePageChange = (page: number) => {
  currentPage.value = page;
  fetchGameList();
};

const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchGameList();
};

const submitForm = async () => {
  try {
    // 处理提交表单逻辑
    const submitData = { ...form };

    // 将数组转换为文本格式存储
    if (Array.isArray(form.platform)) {
      submitData.platform = formatArrayToText(form.platform);
    }
    if (Array.isArray(form.type)) {
      submitData.type = formatArrayToText(form.type);
    }

    console.log('提交:', submitData);

    // 如果是添加操作，删除 gameId 字段或者设置为 null
    if (!form.gameId || form.gameId === 0) {
      // 删除 gameId 字段，让后端自动生成 ID
      delete submitData.gameId;

      // 添加操作 - 使用 POST 方法
      await axios.post('/admin/games/add', submitData);
    } else {
      // 编辑操作 - 使用 PUT 方法
      await axios.put('/admin/games/update', submitData);
    }

    dialogVisible.value = false;
    await fetchGameList(); // 刷新列表
  } catch (error) {
    console.error('提交失败:', error);
  }
};

onMounted(() => {
  fetchGameList();
});
</script>


<style scoped>
.game-management {
  padding: 20px;
}

.toolbar {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
}
</style>
